package com.demo.mysql.base;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

public class DataSourceConfig {

    @Autowired
    private Environment env;

    public DataSourceConfig() {
    }

    protected DataSource getDataSource(String pre) throws Exception {

        DruidDataSource druidDataSource = new DruidDataSource();

        druidDataSource.setUrl(this.env.getRequiredProperty(pre + ".jdbc.url"));
        druidDataSource.setUsername(this.env.getRequiredProperty(pre + ".jdbc.username"));
        druidDataSource.setPassword(this.env.getRequiredProperty(pre + ".jdbc.password"));
        druidDataSource.setDriverClassName(this.env.getRequiredProperty(pre + ".jdbc.driver-class-name"));

        druidDataSource.setMinIdle((Integer) this.env.getProperty("jdbc.minIdle", Integer.class, 2));
        druidDataSource.setMaxWait((long) (Integer) this.env.getProperty("jdbc.maxWait", Integer.class, 60));
        druidDataSource.setMaxActive((Integer) this.env.getProperty("jdbc.maxActive", Integer.class, 20));
        druidDataSource.setInitialSize((Integer) this.env.getProperty("jdbc.initialSize", Integer.class, 2));
        druidDataSource.setPoolPreparedStatements((Boolean) this.env.getProperty("jdbc.poolPreparedStatements", Boolean.class, true));
        druidDataSource.setMinEvictableIdleTimeMillis((long) (Integer) this.env.getProperty("jdbc.minEvictableIdleTimeMillis", Integer.class, 300000));
        druidDataSource.setTimeBetweenEvictionRunsMillis((long) (Integer) this.env.getProperty("jdbc.timeBetweenEvictionRunsMillis", Integer.class, 600000));
        druidDataSource.setConnectionProperties(this.env.getProperty("jdbc.connection.property", "config.decrypt=true"));
        druidDataSource.setRemoveAbandoned(true);
        StatFilter statFilter = new StatFilter();
        statFilter.setSlowSqlMillis(10000L);
        statFilter.setLogSlowSql(true);
        statFilter.setMergeSql(true);
        List<Filter> filters = new ArrayList(1);
        filters.add(statFilter);
        druidDataSource.setProxyFilters(filters);
        druidDataSource.setFilters(this.env.getProperty("jdbc.filter", "config,wall"));
        return druidDataSource;
    }

}
